package cn.rkylin.oms.warehouse.returnStockin.service;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;

import cn.rkylin.apollo.common.util.HttpUtils;
import cn.rkylin.core.service.ApolloService;
import cn.rkylin.oms.aftersale.sysreturn.domain.SysReturnSku;
import cn.rkylin.oms.aftersale.sysreturn.service.ISysReturnService;
import cn.rkylin.oms.aftersale.sysreturn.vo.SysReturnVO;
import cn.rkylin.oms.common.consts.ReturnStockinStatus;
import cn.rkylin.oms.common.consts.YesNoConst;
import cn.rkylin.oms.warehouse.returnStockin.dao.ReturnStockinDAO;
import cn.rkylin.oms.warehouse.returnStockin.dao.ReturnStockinSkuDAO;
import cn.rkylin.oms.warehouse.returnStockin.domain.ReturnStockin;
import cn.rkylin.oms.warehouse.returnStockin.vo.ReturnStockinSkuVO;
import cn.rkylin.oms.warehouse.returnStockin.vo.ReturnStockinVO;
import cn.rkylin.oms.warehouse.shiporder.util.SnCodeExtractor;

/**
 * 退货入库单Service
 * 
 * @author 齐涛
 * @version 1.0
 * @created 28-9-2017 10:51:30
 */
@Repository(value = "returnStockinService")
public class ReturnStockinServiceImpl extends ApolloService implements IReturnStockinService {

    @Value("${job.address}")
    private String jobAddress;

    @Autowired
    private ReturnStockinDAO ReturnStockinDAOImpl;

    @Autowired
    private ReturnStockinSkuDAO ReturnStockinSkuDAOImpl;
    
    @Autowired
    private ISysReturnService sysReturnService;
    
    /**
     * snCodeExtractor:sn号码获取器.
     */
    @Autowired
    private SnCodeExtractor snCodeExtractor;

    /**
     * 查询退货入库单列表
     * 
     * @param page
     *            页号
     * @param rows
     *            页大小
     * @param returnStockinVO
     *            退货入库单VO
     * @return 退货入库单列表
     * @throws Exception
     *             异常
     */
    @SuppressWarnings("rawtypes")
    public PageInfo findByWhere(int page, int rows, ReturnStockinVO returnStockinVO) throws Exception {
        PageInfo<ReturnStockinVO> returnStockinVOList = findPage(page, rows, "pageSelectReturnStockin", returnStockinVO);
        return returnStockinVOList;
    }

    /**
     * 查询退货入库单信息
     *
     * @param returnStockinVO
     *            退货入库单VO
     * @return 退货入库单信息
     * @throws Exception
     *             异常
     */
    public ReturnStockinVO getReturnStockinInfo(ReturnStockinVO returnStockinVO) throws Exception {
        return ReturnStockinDAOImpl.getReturnStockinInfo(returnStockinVO);
    }

    /**
     * 查询退货入库单商品列表
     *
     * @param returnStockinSkuVO
     *            退货入库单商品VO
     * @return 退货入库单商品信息
     * @throws Exception
     *             异常
     */
    public List<ReturnStockinSkuVO> selectReturnStockinSkuList(ReturnStockinSkuVO returnStockinSkuVO) throws Exception {
        List<ReturnStockinSkuVO> returnStockinSkuList = ReturnStockinSkuDAOImpl.selectReturnStockinSkuList(returnStockinSkuVO);
        // 如果是计划退入列表，需要将对应的发货商品SN号添加到表格后面
        if("plan".equalsIgnoreCase(returnStockinSkuVO.getKind())) {
            for (ReturnStockinSkuVO returnStockinSkuVO2 : returnStockinSkuList) {
                /*
                 *  当取计划退入商品的sn号时，需要做：
                 *  1. 从计划退入商品关联到退货单明细商品
                 *  2. 根据退货单明细商品获取sn号（根据退货单明细取计划的sn号时，需要区分订单发货单和补发发货单，复杂点在这里）
                 *  3. 根据计划退入数n，取n个sn号
                 */
                String snCode = getSnCodeByReturnSkuId(returnStockinSkuVO2.getSourceSkuId());
                returnStockinSkuVO2.setSn(snCode);
            }
        }
        return returnStockinSkuList;
        
    }

    private String getSnCodeByReturnSkuId(String returnSkuId) throws Exception {
        String snCode = StringUtils.EMPTY;
        if(StringUtils.isNotEmpty(returnSkuId)) {
            SysReturnSku sysReturnSku = sysReturnService.selectSysReturnSkuByPrimaryKey(returnSkuId);
            SysReturnVO sysReturn = sysReturnService.selectByPrimaryKey(sysReturnSku.getReturnId());
            snCode = sysReturnService.getPlanSnCodeByReturnSku(sysReturnSku,sysReturn);
        }
        return snCode;
    }

    /**
     * 修改退货入库单
     * 
     * @param returnStockinVO
     *            退货入库单VO
     * @return 更新条数
     * @throws Exception
     *             异常
     */
    public int updateReturnStockin(ReturnStockinVO returnStockinVO) throws Exception {
        ReturnStockin returnStockin = new ReturnStockin();
        BeanUtils.copyProperties(returnStockinVO, returnStockin);
        return ReturnStockinDAOImpl.updateReturnStockin(returnStockin);
    }

    /**
     * 取消退货入库单
     *
     * @param stockinId
     *            退货入库单Id
     * @throws Exception
     *             异常
     * @return 取消结果信息
     */
    @SuppressWarnings({ "unchecked", "deprecation" })
    public Map<String, String> cancelReturnStockin(String stockinId) throws Exception {
        Map<String, String> returnMap = new HashMap<String, String>();

        ReturnStockinVO returnStockinVO = new ReturnStockinVO();
        returnStockinVO.setStockinId(stockinId);
        ReturnStockinVO returnStockinData = this.getReturnStockinInfo(returnStockinVO);

        if (ReturnStockinStatus.WAIT_RECEIVE.equals(returnStockinData.getReturnStockinStatus())) { // 待收货
            // 更新退货入库单
            ReturnStockinVO returnStockinInfo = new ReturnStockinVO();
            returnStockinInfo.setStockinId(returnStockinData.getStockinId());
            returnStockinInfo.setCancelStatus(YesNoConst.YES);
            this.updateReturnStockin(returnStockinInfo);
            
            // 更新退货单状态为待审核
            SysReturnVO SysReturnVOUpdate = new SysReturnVO();
            SysReturnVOUpdate.setReturnId(returnStockinData.getSourceId());
            SysReturnVOUpdate.setReturnStatus("a");
            sysReturnService.updateSysReturn(SysReturnVOUpdate);
            
            returnMap.put("success", "true");
        } else if (ReturnStockinStatus.RECEIVING.equals(returnStockinData.getReturnStockinStatus())) { // 收货中
            // 调用奇门接口
            String resJson = HttpUtils.sendByGet(jobAddress + "warehouseDockingController/cancelReturnStockin.action?returnStockInVO="
                    + URLEncoder.encode(JSON.toJSONString(returnStockinData)), null);
            returnMap = JSON.parseObject(resJson, Map.class);
        }

        return returnMap;
    }

    /**
     * 通过来源ID获取退货入库单信息 wangxing add
     * 
     * @param strSourceId
     * @return
     * @throws Exception
     */
    public ReturnStockinVO getReturnStockInInfoBySourceId(String strSourceId) throws Exception {
        return ReturnStockinDAOImpl.getReturnStockInInfoBySourceId(strSourceId);
    }

}
